package com.cross.comparator;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * 比较器工厂
 * 用于比较多种类型的数据,
 * 只能比较同类型的数据
 * 
 * Mar 8, 2009
 * 
 * @author craziness_stone
 */
public class ComparatorFactory {

	private static ComparatorFactory factory = new ComparatorFactory();

	private Map<Class, Comparator> comparorMap = new HashMap<Class, Comparator>(5);

	private ComparatorFactory() {

	}

	private Comparator getComparor(Class clazz) {
		if (!comparorMap.containsKey(clazz)) {
			comparorMap.put(clazz, newComparor(clazz));
		}
		return comparorMap.get(clazz);
	}

	private Comparator newComparor(Class clazz) {
		if (Integer.class.isInstance(clazz)) {
			return new IntegerComparator<Integer>();
		}
		// TODO 添加其它类型的比较器
		return null;
	}

	public static ComparatorFactory getInstance() {
		return factory;
	}

	public int compare(Object src, Object dest) {
		if (src instanceof Integer && dest instanceof Integer) {
			Comparator<Integer> comparator = new IntegerComparator<Integer>();
			return comparator.compare((Integer) src, (Integer) dest);
		}
		Comparator comparator = getComparor(src.getClass());
		if (null == comparator) {
			throw new NullPointerException("未知数据类型");
		}
		return comparator.compare(src, dest);
	}
}